//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.ManagementStudioControls.RegistryManagerModule
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Linq;
    using System.Windows;
    using System.Windows.Input;
    using ManagementStudioServices.Interfaces;
    using Microsoft.Research.ScientificWorkflow.ManagementStudioModels;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;
    using Microsoft.Research.ScientificWorkflow.UIDesigner.WpfComposite;
    using Microsoft.Practices.Unity;

    public class SearchUserPresenter : INotifyPropertyChanged
    {
        private SearchUser searchUserWindow;

        private bool hasUser;

        private bool hasNoUser;

        /// <summary>
        /// Add User command.
        /// </summary>
        public DelegateCommand<object> AddCommand { get; set; }

        /// <summary>
        /// Cancel User command.
        /// </summary>
        public DelegateCommand<object> CancelCommand { get; set; }

        /// <summary>
        /// Test User command.
        /// </summary>
        public DelegateCommand<object> SearchCommand { get; set; }

        /// <summary>
        /// Show Add User command.
        /// </summary>
        public DelegateCommand<object> ShowCommand { get; set; }

        /// <summary>
        /// Name Changes command.
        /// </summary>
        public DelegateCommand<object> NameChangesCommand { get; set; }

        public ObservableCollection<SearchUserModel> SearchResults { get; set; }

        private ObservableCollection<SearchUserModel> AllUsers { get; set; }

        public bool HasNoUser
        {
            get
            {
                return this.hasNoUser;
            }
            set
            {
                this.hasNoUser = !hasUser;
                this.OnNotifyPropertyChanged("HasNoUser");
            }
        }

        public bool HasUser
        {
            get
            {
                return this.hasUser;
            }
            set
            {
                this.hasUser = this.SearchResults.Count > 0;
                this.OnNotifyPropertyChanged("HasUser");
            }
        }
        
        public string SearchText { get; set; }

        public Collection<SearchUserModel> SelectUserModel { get; set; }

        private IUnityContainer container;

        private IRegistryManagerService registryManagerService;

        public SearchUserPresenter(IUnityContainer container, IRegistryManagerService service)
        {
            this.container = container;
            this.registryManagerService = service;

            this.AddCommand = new DelegateCommand<object>(p => this.AddCommandExecuted());
            this.ShowCommand = new DelegateCommand<object>(p => this.ShowCommandExecuted());
            this.CancelCommand = new DelegateCommand<object>(p => this.CancelCommandExecuted());
            this.SearchCommand = new DelegateCommand<object>(p => this.SearchCommandExecuted(), this.CanExecuteSearch);
            this.NameChangesCommand = new DelegateCommand<object>(p => this.NameChangeCommandExecuted());
            this.SearchResults = new ObservableCollection<SearchUserModel>();
            this.AllUsers = new ObservableCollection<SearchUserModel>();
            this.SelectUserModel = new Collection<SearchUserModel>();
            this.GetAllUsers();
        }

        /// <summary>
        /// Handler for Adding New User
        /// </summary>
        private void AddCommandExecuted()
        {
            if (this.SelectUserModel.Count > 0)
            {
                this.CloseWindow();
            }
        }

        /// <summary>
        /// Get all active Users
        /// </summary>
        private void GetAllUsers()
        {
            this.AllUsers = this.registryManagerService.GetAllActiveUsers();
            this.ExecuteSearchCommand();
        }

        /// <summary>
        /// Executes the Search Command
        /// </summary>
        private void ExecuteSearchCommand()
        {
            if (this.SearchCommand != null)
            {
                this.SearchCommand.Execute(null);
            }
        }
        
        /// <summary>
        /// Handler for Search Command Execute
        /// </summary>
        private void SearchCommandExecuted()
        {
            try
            {
                Mouse.OverrideCursor = Cursors.Wait;
                this.SearchResults.Clear();
                IEnumerable<SearchUserModel> results = new List<SearchUserModel>();
                if (string.IsNullOrEmpty(this.SearchText))
                {
                    results = (from model in this.AllUsers select model);
                }
                else
                {
                    results = (from model in this.AllUsers where model.UserName.ToUpperInvariant().Contains(this.SearchText.ToUpperInvariant()) select model);
                }

                foreach (SearchUserModel model in results)
                {
                    this.SearchResults.Add(model);
                }

                this.HasUser = this.SearchResults.Count > 0;
                this.HasNoUser = !this.HasNoUser;
            }

            catch (Exception ex)
            {
                TridentErrorHandler.HandleUIException(ex);
            }
            finally
            {
                Mouse.OverrideCursor = null;
            }
        }
        
        private bool CanExecuteSearch(object obj)
        {
            if (this.SearchText != null)
            {
                if (string.IsNullOrEmpty(this.SearchText.Trim()))
                {
                    this.SearchResults.Clear();
                    this.ExecuteSearchCommand();
                    return false;
                }
                else
                {
                    return true;
                }
            }

            return false;
        }

        ///// <summary>
        ///// Handler for Search Command Execute
        ///// </summary>
        private void NameChangeCommandExecuted()
        {
            this.RaiseCanExecute();
        }

        private void RaiseCanExecute()
        {
            this.SearchCommand.RaiseCanExecuteChanged();
        }

        /// <summary>
        /// Handler for Showing "Add User" Screen
        /// </summary>
        private void ShowCommandExecuted()
        {
            this.searchUserWindow = new SearchUser();
            this.searchUserWindow.Owner = (Window)this.container.Resolve<IRegionManager>("MainWindow");
            this.searchUserWindow.DataContext = this;

            this.searchUserWindow.ShowDialog();
        }

        /// <summary>
        /// Handler for Canceling Add User window
        /// </summary>
        private void CancelCommandExecuted()
        {
            this.SelectUserModel = null;
            this.CloseWindow();
        }

        private void CloseWindow()
        {
            if (this.searchUserWindow != null)
            {
                this.searchUserWindow.Close();
                this.searchUserWindow = null;
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnNotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}
